const knex = require("../../models/knex");
const EduType = require("../../models/type");
const ModelMd = require("../../models/md");
const ModelComment = require("../../models/comment");
const logger = require("../../logger");
const authUser = require("../../models/authUser");
const md5 = require("md5");

const service = {
  async getTypes() {
    return await EduType.list();
  },
  async getMds(body) {
    let tid = null;
    if (body?.slug != "" && body?.slug != "all") {
      // 获取 tid
      const type = await EduType.me().where({
        slug: body?.slug,
      });
      if (type.length === 0) {
        throw Error("文章不存在");
      }
      tid = type[0].id;
    }

    return await ModelMd.page(
      body?.current ?? 1,
      body?.size ?? 10,
      [
        "id",
        "slug",
        "title",
        "uid",
        "tid",
        "tags",
        "views",
        "weight",
        knex.raw("left(md, 200) as conn"),
      ],
      (table) => {
        if (tid) {
          return knex(table)
            .where({
              tid: tid,
            })
            .whereILike("title", `%${body?.title ?? ""}%`)
            .orderBy([
              { column: 'createTime', order: 'desc' }, 
              { column: 'weight', order: 'desc' }
            ]);
        } else {
          return knex(table)
            .whereILike("title", `%${body?.title ?? ""}%`)
            .orderBy([
              { column: 'createTime', order: 'desc' }, 
              { column: 'weight', order: 'desc' }
            ]);
        }
      }
    );
  },
  async getMdBySlug(body) {
    const mds = await ModelMd.me()
      .where({
        slug: body.slug,
      })
      .select();
    if (mds.length === 0) {
      throw Error("文章不存在");
    }
    const md = mds[0];
    const type = await EduType.getById(md.tid);
    const user = await authUser
      .me()
      .select(["id", "name", "account", "email"])
      .where("id", "=", md.uid)
      .first();
    // 计数加一
    await ModelMd.update(md.id, { views: md.views + 1 });
    user.head = `https://cravatar.cn/avatar/${md5(user.email || "")}`;
    return {
      md,
      type,
      user,
    };
  },
  async postComment(params, body) {
    if ((body.text ?? "") === "") {
      throw Error("评论内容为空");
    }
    if ((body.email ?? "") === "") {
      throw Error("邮箱为空");
    }
    if ((body.name ?? "") === "") {
      throw Error("名字为空");
    }
    // 判断文章是否允许评论
    let md = await ModelMd.me()
      .select(["id", "allowComment"])
      .where("id", "=", params.aid);
    if (md.length == 0) {
      throw Error("文章不存在");
    }
    md = md[0];
    if (md.allowComment == "0") {
      throw Error("文章不允许评论");
    }
    const data = {
      email: body?.email || "",
      name: body?.name || "",
      url: body?.url || "",
      text: body?.text || "",
      pid: body?.pid || "0",
      aid: md?.id,
      isAuthor: "0",
      createTime: new Date(),
      updateTime: new Date(),
    };
    return await ModelComment.insert(data);
  },
  async getComments(params, body) {
    logger.info("params ===> " + JSON.stringify(params));
    logger.info("body ===>   " + JSON.stringify(body));
    //
    const retData = await ModelComment.page(
      body?.current ?? 1,
      body?.size ?? 5,
      "*",
      (table) =>
        knex(table)
          .where({
            aid: params.aid,
            pid: 0,
          })
          .orderBy("createTime", "desc")
    );
    if (retData.records.length > 0) {
      for (let index = 0; index < retData.records.length; index++) {
        const element = retData.records[index];
        retData.records[index].childrens = await ModelComment.me()
        .where({ pid: element.id });
      }
    }
    return retData;
  },
};

module.exports = service;
